<template>
<div class="share">
  <div class="header">
    <img class="banner" src="../../assets/GZH/shareBg.png" alt="">
    <div class="rule" @click="showHidePopup"></div>
    <div class="goback" @click="goback">返回</div>
    <div class="shareBtn" @click="shareHandler"></div>
  </div>

  <van-tabs class="card" type="card">
    <van-tab >
      <div slot="title" class="nav-title"><p class="sub-tit">试骑好友</p></div>
      <div class="content">
        <div class="residue-box"  @click="lotteryHandler('1')" v-if="shareData.superShareActivityId&&avtive=='true'">
          <div class="left">
            <p class="residue-num">您还有<span>{{shareData.afterAcceptLotteryChance}}</span>次参与活动的机会</p>
            <p class="residue-hint">去参与<i></i></p>
          </div>
          <div class="right">
            <img src="../../assets/GZH/chance.png"/>
          </div>
        </div>
        <div class="list">
          <div class="item" v-for="(item, index) in shareData.records" :key="index">
            <div class="item-left">
              <img :src="item.avatar" alt="" />
              <div>
                <div class="user-name">{{item.nickName}}</div>
                <div class="user-phone">时间：{{item.createTime}}</div>
              </div>
            </div>
            <div class="item-right1">
              <div class=" item-right redColor" :class="{ 'active': item.state }"
              @click="clearBind(item.state,item.userId)">{{item.state?'解除':item.text}}</div>
              <div class="right-stting" :class="{ 'noActive': item.commonUsed }"  v-if="item.state" @click="as_commonly_user(item)">{{item.commonUsed?'常用':'设置常用'}}</div>
            </div>
          </div>
        </div>
      </div>
    </van-tab>

    <van-tab>
      <div slot="title" class="nav-title"><p class="sub-tit">购车好友</p></div>
      <div class="content">
        <div class="residue-box bg2" @click="lotteryHandler('2')" v-if="shareData.superShareBuyActivityId&&avtive=='true'">
          <div class="left">
            <p class="residue-num">您还有<span>{{shareData.afterBuyLotteryChance}}</span>次参与活动的机会</p>
            <p class="residue-hint">去参与<i></i></p>
          </div>
          <div class="right">
            <img src="../../assets/GZH/chance1.png"/>
          </div>
        </div>
        <div class="list">
          <div class="item" v-for="(item, index) in shareData.buys" :key="index">
            <div class="item-left">
              <img :src="item.avatar" alt="" />
              <div>
                <div class="user-name">{{item.nickName}}</div>
                <div class="user-phone">购车时间：{{item.createTime}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-tab>
  </van-tabs>

  <!-- 分享弹窗 -->
  <div class="popBg1" v-if="shareShow" @click="clearShare">
    <img src="../../assets/GZH/share-ico1.png"/>
  </div>

    <van-popup
      v-model="PopupState"
    >
      <div class="model-main">
        <div class="model-tit">活动规则</div>
        <div class="rule-sjyl" v-html="ruleData">
          <!-- <p><i></i>1、用户可多次试骑，但每个手机号仅限参与一次抽奖活动；</p>
          <p><i></i>2、用户在完成试驾后，将获得一次抽奖机会，100%中取微信现金红包，购车代金券，并有机会赢取九银KING免单大奖；</p>
          <p><i></i>3、用户中取的微信红包将会通过九银官方服务号立即发送，用户需要在服务号内点击领取存入微信余额；
  </p>
          <p><i></i>4、用户中取的购车代金券，可在现场购买指定车型时抵扣对应购车金额，不兑现不找零；</p>
          <p><i></i>5、用户中取免单大奖，需联系现场工作人员领取；</p>
          <p><i></i>6、在法律允许的范围内，活动解释权由九银锂电车负责。</p> -->
        </div>
        <div class="model-btn" @click="showHidePopup">我知道了</div>
      </div>
    </van-popup>
</div>
</template>
<script>
var wx = require("weixin-js-sdk");
// import weixin from './wxConfig.js'
import {Tab, Tabs,Toast,Dialog,Popup } from 'vant';
import md5 from '../../utils/md5.js'
export default {
  components:{
    [Tab.name]:Tab,
    [Tabs.name]:Tabs,
    [Toast.name]:Toast,
    [Dialog.name]:Dialog,
    [Popup.name]:Popup,

  },
  data(){
    return{
      shareImg:require('../../assets/GZH/share-ico.png'),
      token:'',
      webtoken:'',
      carId:'',
      key:'',
      shareData:{
        acceptCount: 0,
        afterAcceptLotteryChance: 0,
        afterBuyLotteryChance: 0,
        buyCount: 0,
        records: [],
        remark: null,
        shareEnable: true,
      },
      shareShow:false,
      ruleData:"",
      PopupState:false,//规则
      errorMessage:'',
      avtive:'',//是否是活动入口
      keyState:'',
    }
  },
  mounted(){
    let _this = this;
      const url = window.location.href;
      this.carId = this.$util.getUrlKey('carId');
      this.token = this.$util.getUrlKey('token');
      this.avtive = this.$util.getUrlKey('avtive');
      this.keyState = this.$util.getUrlKey('keyState');
      let wxMpUserUnion = this.$util.getUrlKey('wxMpUserUnion');
      let code = this.$util.getUrlKey('code');
      if(this.avtive=='false'){
        console.log(1)
        this.share_detail();
        this.rule();
      }else{
         if(wxMpUserUnion=='false'){
           console.log(2)
           let key = localStorage.getItem("key");
            if(key){
              _this.share_detail();
              _this.rule();
              _this.key= key;
            }else{
              if(code){
                //有code静默登录，获取权限
                this.getWeixincofig('config')
                this.share_detail();
                this.rule();
                // this.shareLinkMpKey();
              }else{
                // 无code跳转获取code
                this.getWeixincofig('Login')
              }
            }

        }else{
          console.log(3)
          this.share_detail();
          this.rule();
          this.shareLinkMpKey();
        }
      }


    // let root = process.env.VUE_APP_MAIN;
    // setTimeout(() => {
    //   console.log('分享')
    //   console.log(weixin.wxShare)
    //   weixin.wxShare({
    //     title:'超级试骑，九银KING，抢免单大奖，赢现金红包，百分百中奖！',
    //     desc:'我在现场，九银King超级试骑活动，真的很赞，抢免单大奖，赢现金红包，百分百中奖。快来参与吧！',
    //     link:location.href.split('?')[0]+'activities/share/index.html?shopId='+this.shopId+'&activityId='+this.activityId,
    //     imgUrl:root+ _this.shareImg,
    //   })
    // }, 200);

    // 初始化调用
    setTimeout(()=>{
      _this.create_code();
    },500)
  },
  methods:{
    //设置取消常用人
    as_commonly_user(item){
      let _this = this;
      console.log(item);
      let recordId = item.id;
      let commonUsed = item.commonUsed;
      if(commonUsed){

        return;
        commonUsed = 0;
      }else{
        commonUsed = 1;
      }
      // return;
     this.$api.post2("/exprience_share/v1/authApi/as_commonly_user?recordId="+recordId+'&commonUsed='+commonUsed,{},s => {
        console.log(s);
        if(s.success){
          _this.share_detail();
        }
      },f => {
        Toast(f.errorMessage);
      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*",
        requestPlatform:'wx_app',
        token:this.token
      });
    },
    // 分享key
    shareLinkMpKey(){
      let _this  = this;
      let token = localStorage.getItem("token1");
      console.log(token)
      if(!token){
        console.log(this.keyState!='true',this.keyState)
        if(this.keyState!='true'||!this.keyState){
          this.getWeixincofig('Login');
        }
        return;
      }
      this.$api.get2("/wx/v1/authExpApi/shareLinkMpKey",{},s => {
        console.log(s);
        if(s.success){
          _this.key = s.module;
          localStorage.setItem('key', s.module);
        }
      },f => {
        Toast(f.errorMessage);
      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*",
        requestPlatform:'wx_app',
        expToken:token
      });
    },
    // 返回
    goback(){
       wx.miniProgram.reLaunch({url: '/pages/tabBar/home/home'})
    },
    //结束分享
    clearBind(state,id){
      let _this  = this;
      if(!state){
        return;
      }
      this.$api.post2("/exprience_share/v1/authApi/stop_exprience?carId="+this.carId+'&userId='+id,{},s => {
        console.log(s);
        if(s.success){
          _this.share_detail();
        }
      },f => {
        Toast(f.errorMessage);
      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*",
        requestPlatform:'wx_app',
        token:this.token
      });
    },
    lotteryHandler(type){
      let _this = this;
      let shareData = this.shareData
      if(type=='1'){
        console.log('试骑奖励次数',_this.shareData.afterAcceptLotteryChance)
        if(_this.shareData.afterAcceptLotteryChance){
          window.location.replace(_this.$util.root1+'activities/prod/sharePmd.html?activityId='+shareData.superShareActivityId+'&carId='+this.carId+'&shopId='+shareData.shopId+'&key='+this.key+'&token='+this.token+'&timestamp='+ new Date().getTime()+Math.random())
        }else{
          Toast('暂无抽奖机会！');
        }
      }else if(type=='2'){
          console.log('购车奖励次数',_this.shareData.afterBuyLotteryChance)
        if(_this.shareData.afterBuyLotteryChance){
          window.location.replace(_this.$util.root1+'activities/prod/sharePmd.html?activityId='+shareData.superShareBuyActivityId+'&carId='+this.carId+'&shopId='+shareData.shopId+'&key='+this.key+'&token='+this.token+'&timestamp='+ new Date().getTime()+Math.random())
        }else{
          Toast('暂无抽奖机会！');
        }
      }
    },
    // 显示隐藏活动规则
    showHidePopup(){
      this.PopupState = !this.PopupState;
    },
  // 活动规则
    rule(){
      let _this = this;
        this.$api.post2("/global/v1/text?key=SUPER_SHARE_REMARK",{},s => {
          console.log(s);
          // _this.ruleData = s.module
      },f => {

      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*"
      });
    },
    // 获取微信配置
    getWeixincofig(str){
      let _this = this;
      // process.env.VUE_APP_MAIN
      // escape()
      let main = location.href.split("#")[0];
      if(main.indexOf('https')==0){
        // main='http://jike.xingjiakeji.com/'
        main='https://h5-jike.6glz.com/'
      }
      let url = escape(main+'#/oneDayShare')+encodeURIComponent('?carId='+this.carId+'&token='+this.token+'&wxMpUserUnion=false&avtive=true'+'&keyState=true')
      console.log('url',url)
      // return;
      // let url = encodeURIComponent(location.href.split("#")[0]+'#/oneDayShare?carId='+this.carId+'&token='+this.token+'&wxMpUserUnion=false');
      // let url = 'http://sunjinxiang.wicp.vip/#/testDrive';
      this.$api.get2("/wx/v1/jsapi_sigin?url=" + url,{},s => {
          console.log(s);
          let data = s.module;
          if(str=='Login'){

            // 微信网页授权snsapi_base，snsapi_userinfo区别和实现
            window.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid='+data.appId+'&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect')
          }else{
            _this.wxLogin();
          }
      },f => {

      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*"
      });
    },
    // 登录
    wxLogin(){
      let _this = this;
      let code = this.$util.getUrlKey('code');
      console.log(code)
      var SECRET = process.env.VUE_APP_SECRET;
      let sign = md5("code=" + code + "&secret=" +SECRET ).toLowerCase()
      this.$api.get2("/wx/v1/login?code=" + code+'&sign='+sign,{},s => {
          console.log(s);
          let data = s.module;
          localStorage.setItem('token1', data);
          _this.shareLinkMpKey();
          // _this.key = data.key;
          // _this.userInfoFunc(data,'phone');
      },f => {
        console.log('f',f)
        if(f.resultCode=='40029'||f.resultCode=='40163'||f.resultCode=='42003'||f.resultCode=='41008'){
          // window.location.href = encodeURIComponent(process.env.VUE_APP_MAIN+'#/oneDayShare')
        }else{
          Toast(f.errorMessage);
        }
      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*"
      });
    },
    clearShare(){
      this.shareShow = false
    },
    shareHandler(){
      if(this.errorMessage){
        Toast(this.errorMessage);
      }else{
        this.shareShow = true;
        setInterval(() => {
          this.create_code();
        }, 5000)
      }

    },
    // 超级分享-创建试骑分享
    //创建分享
    create_code(){
      let _this  = this;
      this.$api.post2("/exprience_share/v1/authApi/create_code?carId="+this.carId,{},s => {
          console.log(s);
          if(s.module){
            let name = _this.shareData.userNickName||'车主'
          //  分享链接
          let url='https://jike.xingjiakeji.com/qrcode/index.html?no=share='+s.module;
          wx.miniProgram.postMessage({
            data: {
              id:1,
              title: name+'邀请您使用他的爱车，如需使用请猛戳链接',
              wx_url: url,
              shareCode:s.module
            }
          })
          }
      },f => {
        _this.errorMessage = f.errorMessage
        Toast(f.errorMessage);
      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*",
        requestPlatform:'wx_app',
        token:this.token
      });
    },
    //分享详情
    share_detail(){
      let _this = this;
        this.$api.post2("/exprience_share/v1/authApi/share_detail?carId="+this.carId,{},s => {
          console.log(s);
          if(s.module){
            let shareData = s.module;
            let records = s.module.records;
            if(shareData.records){
              for(let i=0;i<records.length;i++){
                if(!records[i].state&&!shareData.superShareActivityId){
                  shareData.records[i].text="已结束"
                  console.log('无抽奖活动')
                }else if(!records[i].state&& shareData.superShareActivityId){
                  if(shareData.limitCheck){
                    shareData.records[i].text="抽奖机会到达上限"
                    console.log('到达上限')
                  }else{
                    if(records[i].chanceState==1){
                      shareData.records[i].text="机会已使用"
                      console.log('机会已使用')
                    }else if(records[i].chanceState==-1){
                      shareData.records[i].text = records[i].chanceRemark;
                       console.log('失效原因')
                    }else if(records[i].chanceState==0){
                      shareData.records[i].text = '机会+1';
                      console.log('加机会')
                    }
                  }

                }
              }
              _this.shareData=shareData;
            }
           _this.shareData=s.module;
           _this.ruleData = s.module.remark
          }
      },f => {
        // Toast(f.errorMessage);
      },{
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "*/*",
        requestPlatform:'wx_app',
        token:this.token
      });
    },
  }
}
</script>
<style>
  body, html {
    width:100%;
    height:auto;
  }
.card{
  width:100%;
  height:60px;
}
.card.van-tabs--card{
  height:60px;
  padding-top:60px;
}
.card .van-tabs__nav--card{
  margin:0;
  border:none;
}
.card .van-tabs__wrap,.card .van-tabs__nav--card{
  height:60px;
}
.card .van-tabs__nav--card .van-tab{
  line-height: auto;
}
.card .van-tab {
  color: #adadad;
  background-color: #333;
  border-right:none;
}
.card .van-tab.van-tab--active{
    color: #333;
    background-color: #ffd617;
}
.card  .nav-title{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width:100%;
  height:100%;
}
.card .van-tab>div{
  height:100%;
}
.card .sub-tit{
  font-weight:600;
  font-size:14px;
  line-height: 22px;
}
.card .num{
  font-size:18px;
  line-height:22px;
  font-weight:600;
}
.van-popup{
  position:absolute;
}

.rule-sjyl{
  text-align: left;
}
.rule-sjyl p{
  position:relative;
}
.rule-sjyl i{
  position: absolute;;
  top:7px;
  left:-10px;
  display: inline-block;
  width:5px;
  height:5px;
  border-radius:12px;
  background: #ff5e37;
}
</style>

<style scoped lang="scss">
.van-popup{
  width:300px;
  padding:20px;
  // min-height:300px;
  border-radius: 16px;
}
.share{
  width:100%;
}
.banner,.header{
  position:relative;
  width:100%;
  height:398px;
}
.goback{
  position: absolute;
  top:40px;
  left:0px;
  width:50px;
  height:30px;
  font-size:12px;
  line-height:30px;
  color:#fff;
  border-radius: 0 40px 40px 0;
  background: rgba(0, 0, 0, 0.5);
}
.rule{
  position: absolute;
  top:4px;
  right:4px;
  width:100px;
  height:40px;
  // border:1px solid red;
}
.shareBtn{
  position: absolute;
  bottom:21px;
  left:50%;
  width:200px;
  height:60px;
  margin-left:-100px;
  // border:1px solid red;
}
.content{
  width:100%;
  overflow: hidden;
  min-height:300px;
  text-align: left;
  background:#fff;
}
.residue-box{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width:94%;
  height:70px;
  margin:15px auto;
  border-radius: 8px;
  background: #f0f0f2;
}
.residue-box.bg2{
  background: #d6fff1;
}
.left{
  flex:1;
  padding-left:13px;
}
.right{
  width:109px;
  height:63px;
  margin-right:8px;
}
.right img{
  width:100%;
  height:100%;
}
.residue-num{
  font-weight:500;
  font-size:16px;
  color:#333;
}
.residue-num span{
  margin-left:6px;
  margin-right:6px;
  font-weight:600;
  color:#ff1e39;
}
.residue-hint{
  width:60px;
  height:20px;
  margin-top:5px;
  text-align: center;
  font-size:11px;
  line-height: 20px;
  background: #fff;
  color:#ff1e39;
}
.residue-hint i{
  position:relative;
  top:2px;
  left:5px;
  display:inline-block;
  width:0px;
  height:0px;
  border:5px solid #fff;
  border-left:5px solid red;
}
.list{
  width:100%;
  min-height:300px;
  background:#fff;
}
.item{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width:94%;
  height:75px;
  margin:0 auto;
  font-size:12px;
  border-bottom:1px solid #eee;
}
.item img{
  width:40px;
  height:40px;
  border:1px solid red;
  border-radius: 40px;
}
.item-left{
  flex:1;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
.user-name{
  margin-left:9px;
  font-size:14px;
  font-weight:500;
  color:#333;
}
.user-phone{
  margin-left:9px;
  font-size:12px;
  color:#999;
}
.item-right1{
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  width:120px;
  // border:1px solid red;
}
.item-right{
  font-size:12px;
}
.right-stting{
  width:55px;
  height:25px;
  margin-left:7px;
  border-radius: 5px;
  line-height: 25px;
  text-align: center;
  background:#ff1e39;
  color:#fff;
}
.noActive{
  width:25px;
  background:none;
  color:#666;
}
.redColor{
  color:#ff1e39;
}
.active{
  width:55px;
  height:25px;
  border-radius: 5px;
  line-height: 25px;
  text-align: center;
  background:#ff1e39;
  color:#fff;
}
.popBg1{
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 201;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.7);
}
.popBg1 img{
  position: absolute;
  right:60px;
  top:0;
  width:260px;
  height:250px;
}
.model-main .rule-sjyl{
  position: relative;
  margin-top:10px;
  font-size:12px;
  line-height: 22px;
  color:#666;
}

.model-btn{
  width: 150px;
  height: 46px;
  margin: 20px auto;
  font: 13px/46px "Mircosoft YaHei";
  text-align: center;
  border-radius: 46px;
  background: #ff5d2e;
  color: #fff;
  box-shadow: 0 2px 25px 0 #ff7e59;
}
</style>